chrome.sidePanel
	.setPanelBehavior({ openPanelOnActionClick: true })
	.catch((error) => console.error(error));

const openSidePanel = () => {
	// 获取当前tab
	chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
		if (tabs && tabs.length !== 0 && tabs[0].id) {
			chrome.sidePanel.open({ tabId: tabs[0].id });
		}
	});
};
let contentPort: chrome.runtime.Port | null = null;
let sidePanelPort: chrome.runtime.Port | null = null;
console.log(
	"Initial contentPort status:",
	contentPort ? "connected" : "disconnected"
);
console.log(
	"Initial sidePanelPort status:",
	sidePanelPort ? "connected" : "disconnected"
);

chrome.runtime.onMessage.addListener((request, sender) => {
	console.log("onMessage", request, sender);
	if (request.action === "content") {
		if (sidePanelPort) {
			sidePanelPort.postMessage(request);
		} else {
			openSidePanel();
		}
	}
});

// 收到 content-script 的端口
chrome.runtime.onConnect.addListener((fromPort) => {
	// if (fromPort.name === "contentSideBridge") {
	// 	contentPort = fromPort;
	// 	fromPort.onMessage.addListener((msg) => {
	// 		console.log("contentSideBridge", msg);
	// 		if (sidePanelPort) {
	// 			sidePanelPort.postMessage(msg);
	// 		} else {
	// 			openSidePanel();
	// 		}
	// 	});
	// 	fromPort.onDisconnect.addListener(() => {
	// 		contentPort = null;
	// 	});
	// }

	if (fromPort.name === "sidePanelBridge") {
		sidePanelPort = fromPort;
		fromPort.onMessage.addListener((msg) => {
			console.log("sidePanelBridge", msg);
		});
		fromPort.onDisconnect.addListener(() => {
			sidePanelPort = null;
		});
	}
});
